var resultAll = '';


// 选择input上传的值
var orderIdArray = [];
// 需要上传的图片加数据综合
var finallyArray = [];
var newAllStr = [];

var newTime = timeAll(); // 定义一个时间戳


//  获取成交订单的列表 （从订单管理中选择订单）
function getDealList() {
    //  拼接，加密，变大写，传值
    var timestamp = 'timeStamp:' + newTime + 'BM' + 'pageNum:' + 1 + 'BM' + 'pageSize:' + 100 + 'BM' + 'startDate:' + '' + 'BM' + 'endDate:' + '' + 'BM' + 'orderStatus:' + 190 + 'BM';
    var signs = md5(timestamp);
    signs = signs.toUpperCase();
    // 发送请求
    $.ajax({
        type: 'get',
        url: webUrl3 + '/store/paltformTransaction/getOrderList',
        data: {
            'timeStamp': newTime,
            'sign': signs,
            'pageNum': 1,   // 等分页封装好在上传；下拉加载更多
            'pageSize': 100,
            'startDate': '',
            'endDate': '',
            'orderStatus': 190
        },
        dataType: 'JSON',
        async: false,
        success: function (data) {
            console.log(data)
            $('#listStr').html(data);
            if (data.status == 200) {
                //  拼接字符串，拼接成交订单详情信息
                for (var i = 0; i < data.data.length; i++) {
                    var item = data.data[i];

                    var orderList = '<form class="itemPPP" id=' + 'form' + i + ' action="">' +
                        '<span>' + item.dealDate + '</span> 上门回收<input type="checkbox" value=' + item.orderId + ' name="IMEI" /><br/>' +
                        '<div class="iphoneDetail">' +
                        '<div>' + item.productName + '</div>' +
                        '<div>预估价:￥' + item.dealPrice + '</div>' +
                        '</div>' +
                        '<div style="display: flex;margin-top: 10px">ime串号: <input class="ime-input" type="text" name="orderId" value="" /></div><br />' +
                        '<form method="post" id="uploadForm" enctype="multipart/form-data">' +
                        '<div class="img-box full">' +
                        '<section class="img-section">' +
                        '<p style="width: 100%;line-height: 30px"><span class="up-span">请添加三张实拍图</span></p>' +
                        '<div class="z_photo upimg-div clear">' +
                        '<section class="z_file fl">' +
                        '<img src="../addimg/upImg/addPick.png" class="add-img">' +
                        '<input type="file" name="file"  id=' + 'fileID' + i + '  class="file" value="" accept="image/jpg,image/jpeg,image/png,image/bmp" multiple/>' +
                        '</section>' +
                        '</div>' +
                        '</section>' +
                        '</div>' +
                        '</form>' +
                        '<aside class="mask works-mask">' +
                        '<div class="mask-content">' +
                        '<p class="del-p">您确定要删除作品图片吗？</p>' +
                        '<p class="check-p"><span class="del-com wsdel-ok">确定</span><span class="wsdel-no">取消</span></p>' +
                        '</div>' +
                        '</aside>' +
                        '</form>' + '<div style="width: 100%;height: 5px;margin-top:10px;background: #F1F1F1"></div>';

                    $('#listStr').append(orderList);
                }
            } else if (data.status == 300) {
                document.location.href = '../../html/login.html';
            } else {
                alert(data.msg)
            }
        }
    })
}


var fileList = '';
$(function () {
    var delParent;
    var defaults = {
        fileType: ["jpg", "png", "bmp", "jpeg"],   // 上传文件的类型
        fileSize: 1024 * 1024 * 10                  // 上传文件的大小 10M
    };
    /*点击图片的文本框*/
    $(".file").change(function () {
        var idFile = $(this).attr("id");
        var file = document.getElementById(idFile);
        var imgContainer = $(this).parents(".z_photo"); //存放图片的父亲元素
        fileList = file.files; //获取的图片文件
        var input = $(this).parent();//文本框的父亲元素
        var imgArr = [];
        //遍历得到的图片文件
        var numUp = imgContainer.find(".up-section").length;
        var totalNum = numUp + fileList.length;  //总的数量
        if (fileList.length > 3 || totalNum > 3) {
            alert("上传图片数目不可以超过3个，请重新选择");  //一次选择上传超过5个 或者是已经上传和这次上传的到的总数也不可以超过5个
        }
        else if (numUp < 3) {
            fileList = validateUp(fileList);
            for (var i = 0; i < fileList.length; i++) {
                var imgUrl = window.URL.createObjectURL(fileList[i]);

                imgArr.push(imgUrl);

                var $section = $("<section class='up-section fl loading'>");
                imgContainer.prepend($section);
                var $span = $("<span class='up-span'>");
                $span.appendTo($section);

                var $img0 = $("<img class='close-upimg'>").on("click", function (event) {
                    event.preventDefault();
                    event.stopPropagation();
                    $(".works-mask").show();
                    delParent = $(this).parent();
                });
                $img0.attr("src", "../../sellUpstream/addimg/upImg/cha.png").appendTo($section);
                var $img = $("<img class='up-img up-opcity'>");
                $img.attr("src", imgArr[i]);
                $img.appendTo($section);
                var $p = $("<p class='img-name-p'>");
                $p.html(fileList[i].name).appendTo($section);
                var $input = $("<input id='taglocation' name='taglocation' value=" + fileList[i].name + " type='hidden'>");
                $input.appendTo($section);
                var $input2 = $("<input id='tags' name='tags' value='' type='hidden'/>");
                $input2.appendTo($section);
            }
        }
        setTimeout(function () {
            $(".up-section").removeClass("loading");
            $(".up-img").removeClass("up-opcity");
        }, 450);
        numUp = imgContainer.find(".up-section").length;
        if (numUp >= 3) {
            $(this).parent().hide();
        }
    });


    $(".z_photo").delegate(".close-upimg", "click", function () {
        $(".works-mask").show();
        delParent = $(this).parent();
    });

    $(".wsdel-ok").click(function () {
        $(".works-mask").hide();
        var numUp = delParent.siblings().length;
        if (numUp < 4) {
            delParent.parent().find(".z_file").show();
        }
        delParent.remove();
    });

    $(".wsdel-no").click(function () {
        $(".works-mask").hide();
    });

    function validateUp(files) {
        var arrFiles = [];//替换的文件数组
        for (var i = 0, file; file = files[i]; i++) {
            //获取文件上传的后缀名
            var newStr = file.name.split("").reverse().join("");
            if (newStr.split(".")[0] != null) {
                var type = newStr.split(".")[0].split("").reverse().join("");
                if (jQuery.inArray(type, defaults.fileType) > -1) {
                    // 类型符合，可以上传
                    if (file.size >= defaults.fileSize) {
                        alert(file.size);
                        alert('您这个"' + file.name + '"文件大小过大');
                    } else {
                        // 在这里需要判断当前所有文件中
                        arrFiles.push(file);
                    }
                } else {
                    alert('您这个"' + file.name + '"上传类型不符合');
                }
            } else {
                alert('您这个"' + file.name + '"没有类型, 无法识别');
            }
        }
        return arrFiles;
    }
})


function upMoreImg() {
    //TODO 以下几个值请确保填上再调用示例里的sdk方法
    //具体可以到https://console.qcloud.com/cos 进行查看
    var bucket = 'test';
    var appid = '1255372231';
    var sid = 'AKIDxvy2CLaG1gBVftOo48SlwyCIEzCMN9zh';
    var skey = 'hJrEQSJ6iCVfeScdTIwOgqsmW5UjnfS5';
    var region = 'sh';
    //TODO 以上几个值请确保填上再调用示例里的sdk方法

    var myFolder = '/';//需要操作的目录

    //初始化逻辑
    //特别注意: JS-SDK使用之前请先到console.qcloud.com/cos 对相应的Bucket进行跨域设置
    var cos = new CosCloud({
        appid: appid,// APPID 必填参数
        bucket: bucket,//bucketName 必填参数
        region: region,//地域信息 必填参数 华南地区填gz 华东填sh 华北填tj
        getAppSign: function (callback) {//获取签名 必填参数


            //下面简单讲一下获取签名的几种办法，签名请做一次 url encode
            //1.搭建一个鉴权服务器，自己构造请求参数获取签名，推荐实际线上业务使用，优点是安全性好，不会暴露自己的私钥
            /**
             $.ajax('SIGN_URL').done(function (data) {
                        var sig = data.sign;
                        callback(sig);
                    });
             **/


                //2.直接在浏览器前端计算签名，需要获取自己的accessKey和secretKey, 一般在调试阶段使用
            var self = this;
            var random = parseInt(Math.random() * Math.pow(2, 32));
            var now = parseInt(new Date().getTime() / 1000);
            var e = now + 60; //签名过期时间为当前+60s
            var path = '';//多次签名这里填空
            var str = 'a=' + self.appid + '&k=' + sid + '&e=' + e + '&t=' + now + '&r=' + random +
                '&f=' + path + '&b=' + self.bucket;

            var sha1Res = CryptoJS.HmacSHA1(str, skey);//这里使用CryptoJS计算sha1值，你也可以用其他开源库或自己实现
            var strWordArray = CryptoJS.enc.Utf8.parse(str);
            var resWordArray = sha1Res.concat(strWordArray);
            var res = resWordArray.toString(CryptoJS.enc.Base64);

            setTimeout(function () {//setTimeout模拟一下网络延迟的情况
                callback(res);
            }, 1000);


            //3.直接复用别人算好的签名字符串, 一般在调试阶段使用
            //callback('YOUR_SIGN_STR')

        },
        getAppSignOnce: function (callback) {//单次签名，参考上面的注释即可
            var self = this;
            var random = parseInt(Math.random() * Math.pow(2, 32));
            var now = parseInt(new Date().getTime() / 1000);
            var e = 0; //单次签名 expire==0
            var path = self.path;
            var str = 'a=' + self.appid + '&k=' + sid + '&e=' + e + '&t=' + now + '&r=' + random +
                '&f=' + path + '&b=' + self.bucket;

            var sha1Res = CryptoJS.HmacSHA1(str, skey);//这里使用CryptoJS计算sha1值，你也可以用其他开源库或自己实现
            var strWordArray = CryptoJS.enc.Utf8.parse(str);
            var resWordArray = sha1Res.concat(strWordArray);
            var res = resWordArray.toString(CryptoJS.enc.Base64);

            setTimeout(function () {//setTimeout模拟一下网络延迟的情况
                callback(res);
            }, 1000);
        }
    });

    var resultStr = '';


    var successCallBack = function (result) {
        resultStr = resultStr + result.data.source_url + ',';
        var results2 = resultStr.split(',');
        if (results2.length == 4) {
            resultStr = (resultStr.substring(resultStr.length - 1) == ',') ? resultStr.substring(0, resultStr.length - 1) : resultStr;
            newAllStr.push(resultStr);
            if (newAllStr.length = finallyArray.length) {
                ajaxText();
            }
            resultStr='';
            // /store/paltformTransaction/postBatchesToUpstream
        } else {
            dialog('正在上传');
        }
    };

    // 上传图片接口调用
    function ajaxText() {
        var imgArrayDDDD ='';
        for (var j = 0; j < finallyArray.length; j++) {
            imgArrayDDDD=imgArrayDDDD+finallyArray[j] + resultStr+"*";
        }

        imgArrayDDDD = (imgArrayDDDD.substring(imgArrayDDDD.length - 1) == '*') ? imgArrayDDDD.substring(0, imgArrayDDDD.length - 1) : imgArrayDDDD;


        console.log(imgArrayDDDD);


        var timeStamp = "timeStamp:" + newTime + "BM" + "orderInfos:" + imgArrayDDDD + "BM" ;
        var signs = md5(timeStamp);

        signs = signs.toUpperCase();

        $.ajax({
            type: "post",
            url: webUrl + "paltformTransaction/postBatchesToUpstream",
            data: {
                "timeStamp": newTime,
                "orderInfos": imgArrayDDDD,
                "sign": signs,
            },
            dataType: "JSON",
            async: false,
            success: function (data) {
                if (data.status == 200) {
                    var resultAll='';
                    //  获取多个ID
                    $.each($('input:checkbox'), function () {
                        if (this.checked) {
                            // 获取都值后；将每一个值后面都加一个逗号；并且拼接起来
                            resultAll = resultAll + $(this).val() + ',';
                        }
                    })
                    //  去除拼接就得字符串的最后一位的逗号
                    resultAll = resultAll.substr(0, resultAll.length - 1)
                    console.log(resultAll);

                    // document.location.href = '../../sellUpstream/submitSuccess/submitSuccess.html?strArray='+resultAll;

                } else if (data.status == 300) {
                    document.location.href = '../../html/login.html';
                } else if (data.status == 500) {
                    dialog(data.msg);
                }
            },
            error: function (data) {
                //弹出报错内容　　
                dialog("服务器异常")
            }
        })

    }

    var errorCallBack = function (result) {
        result = result || {};
        console.log('request error:', result && result.message);
        $("#result").val(result.responseText || 'error');
    };

    var progressCallBack = function (curr, sha1) {
        var sha1CheckProgress = ((sha1 * 100).toFixed(2) || 100) + '%';
        var uploadProgress = ((curr || 0) * 100).toFixed(2) + '%';
        var msg = 'upload progress:' + uploadProgress + '; sha1 check:' + sha1CheckProgress + '.';
    };

    var lastTaskId;
    var taskReady = function (taskId) {
        lastTaskId = taskId;
    };

    var orderId = "";
    var finallyStr = "";


    var imgArrayService = [];
    var imgArrayServiceStr = "";

    $(document).ready(function () {
        $("#uploadFile").click(function () {
            orderIdArray = [];
            finallyArray = [];
            newAllStr = [];
            imgArrayService = [];
            $("input[name='IMEI']:checkbox:checked").each(function () {
                orderId = $(this).parent().serializeArray();
                orderIdArray.push(orderId);
            });
            if (orderIdArray.length > 0) {
                for (var i = 0; i < orderIdArray.length; i++) {
                    var orderItem = orderIdArray[i];
                    if (orderItem.length == 8) {
                        for (var j = 0; j < orderItem.length; j++) {
                            if (orderItem[1].value == "") {
                                dialog("请将信息填写完整");
                            } else {
                                finallyStr =  orderItem[0].value + ";"+ orderItem[1].value + ";";
                                imgArrayServiceStr = orderItem[2].value + ',' + orderItem[4].value + "," + orderItem[6].value;
                            }
                        }
                        finallyArray.push(finallyStr);
                        imgArrayService.push(imgArrayServiceStr);
                    } else {
                        dialog("请将信息填写完整");
                    }
                }

                if (finallyArray.length > 0) {
                    // console.log(finallyArray);
                    // console.log(imgArrayService);

                    for (var h = 0; h < imgArrayService.length; h++) {
                        var imgThirdStr = imgArrayService[h];
                        var upimg = imgThirdStr.split(',');

                        if (upimg.length * imgArrayService.length == 3 * orderIdArray.length) {
                            for (var k = 0; k < upimg.length; k++) {
                                cos.uploadFile(successCallBack, errorCallBack, progressCallBack, bucket, myFolder + upimg[k], upimg[k], 0, taskReady);//insertOnly==0 表示允许覆盖文件 1表示不允许
                            }
                        } else {
                            dialog("请将信息填写完整")
                        }

                    }

                } else if (finallyArray.length = 0) {
                    dialog("你还没有选择任何订单")
                }
            } else {
                dialog("请至少选择一个订单")
            }
            finallyStr = '';
            orderId = "";
            imgArrayServiceStr = ''
        });
    });
}